package com.ts.api.http.platform.biz;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.gitee.apanlh.util.base.ChooseEq;
import com.gitee.apanlh.util.base.CollUtils;
import com.gitee.apanlh.util.base.Eq;
import com.gitee.apanlh.util.base.MapUtils;
import com.gitee.apanlh.util.dataformat.JsonUtils;
import com.gitee.apanlh.util.valid.ValidParam;
import com.gitee.apanlh.web.model.vo.RequestVO;
import com.ts.api.common.util.ApiDictUtils;
import com.ts.api.http.platform.entity.apply.ApiPlatApplyJiYongHua;
import com.ts.api.http.platform.entity.dataexchange.ApiPlatDataExchangeJiYongHua;
import com.ts.api.module.api.convert.core.annotation.ApiPlan;
import com.ts.api.module.api.convert.core.annotation.ApiPlanConvertType;
import com.ts.api.module.api.convert.core.entity.ApiApplyParameter;
import com.ts.api.module.api.convert.core.entity.ApiBizStatus;
import com.ts.api.module.api.convert.core.entity.ApiDataExchangeParameter;
import com.ts.api.module.api.convert.platform.entity.*;
import com.ts.api.module.api.convert.platform.handler.ApiPlatformPhoneMd5ConvertHandler;
import com.ts.api.module.api.entity.ApiProtocol;
import lombok.extern.slf4j.Slf4j;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.math.BigDecimal;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * 吉用花采-安心分期MD5全流程出28
 * @author 李源聪
 * @since 2025年06月18日 14:59
 */
@Slf4j
@ApiPlan(productId = "255", type = ApiPlanConvertType.PLAT_PHONE_MD5)
public class ApiPlatJiYongHuaConvert implements ApiPlatformPhoneMd5ConvertHandler {

    private static final String KEY = "bqYm4am7Z4jzWufF";
    private static final String APP_KEY = "bqYm4am7Z4jzWufF";
    private static final String CHANNEL_CODE = "axfq-q";

    @Override
    public RespPlatformPhoneMd5DataExchange respDataExchange(String respJson) {

        JSONObject jsonObject = JsonUtils.get(respJson);
        if (jsonObject == null) {
            return RespPlatformPhoneMd5DataExchange.ofFail();
        }
        String code = jsonObject.getString("code");
        if (!Eq.str(code, "0")) {
            return RespPlatformPhoneMd5DataExchange.ofFail();
        }

        JSONObject resData = JsonUtils.get(respJson).getJSONObject("data");
        if (ValidParam.isEmpty(resData)) {
            return RespPlatformPhoneMd5DataExchange.ofFail();
        }

        JSONArray resProtocolList = resData.getJSONArray("agreements");
        BigDecimal price = resData.getBigDecimal("price");
        String companyName = resData.getString("companyName");
        String productName = resData.getString("productName");

        List<ApiProtocol> protocolList = CollUtils.newArrayList(newList -> {
            if (ValidParam.isNotEmpty(resProtocolList)) {
                for (int i = 0; i < resProtocolList.size(); i++) {
                    JSONObject protocolObject = resProtocolList.getJSONObject(i);
                    ApiProtocol protocol = new ApiProtocol();
                    protocol.setProtocolName(protocolObject.getString("protocolName"));
                    protocol.setProtocolUrl(protocolObject.getString("protocolUrl"));
                    newList.add(protocol);
                }
            }
        });

        RespPlatformPhoneMd5DataExchange result = RespPlatformPhoneMd5DataExchange.ofSuc();
        result.setPrice(price);
        result.setDisplayName(companyName);
        result.setProductName(productName);
        result.setProtocolList(protocolList);
        return result;
    }

    @Override
    public Object dataExchange(ApiDataExchangeParameter apiDataChangeMessage) throws Exception {

        ApiPlatDataExchangeJiYongHua apiPlatDataExchange = new ApiPlatDataExchangeJiYongHua();

        apiPlatDataExchange.setPhoneMd5(apiDataChangeMessage.getPhoneMd5());
        // 城市代码
        apiPlatDataExchange.setAreaCode(apiDataChangeMessage.getAreaCode());
        // 城市
        apiPlatDataExchange.setCity(apiDataChangeMessage.getCity());

        //  年龄(21岁-55岁)
        String age = ApiDictUtils.convertAge(apiDataChangeMessage.getAge());
        apiPlatDataExchange.setAge(age);

        //sex 性别(1:为男,2:为女)
        // sex 性别
        // 0 男
        // 1 女
        // 2 未知
        String sex = apiDataChangeMessage.getSex();
        String sexChoose = ChooseEq.create()
                .when(sex, "0", "1")
                .when(sex, "1", "2")
                .end("1");
        apiPlatDataExchange.setSex(sexChoose);

        // loanAmount 贷款额度1（30000）2（50000）3（100000）4（200000）
        // loanAmount 贷款金额
        // 1 3万以下
        // 2 5万-10万
        // 3 10万-20万
        // 4 20万以上
        String loanAmount = apiDataChangeMessage.getLoanAmount();
        String loanAmountValue = ChooseEq.create()
                .when(loanAmount, "1", "1")
                .when(loanAmount, "2", "2")
                .when(loanAmount, "3", "3")
                .when(loanAmount, "4", "4")
                .end("1");
        apiPlatDataExchange.setLoanAmount(loanAmountValue);

        // hasHouse 是否有房，1-有、0-无
        // realEstateInfo 房产情况
        // 1 无房产
        // 2 有房不抵押
        // 3 有房可抵押
        // 4 有房产
        // 5 有按揭房产
        // 6 有全款房产
        String realEstateInfo = apiDataChangeMessage.getRealEstateInfo();
        String realEstateInfoValue = ChooseEq.create()
                .when(realEstateInfo, "1", "0")
                .when(realEstateInfo, "2", "1")
                .when(realEstateInfo, "3", "1")
                .when(realEstateInfo, "4", "1")
                .when(realEstateInfo, "5", "1")
                .when(realEstateInfo, "6", "1")
                .end("0");
        apiPlatDataExchange.setRealEstateInfo(realEstateInfoValue);

        // vehicle 名下车产1（有车产）2（无车产）
        // carInfo 车辆情况
        // 1 无车产
        // 2 有车不抵押
        // 3 有车可抵押
        // 4 有车产
        String carInfo = apiDataChangeMessage.getCarInfo();
        String carInfoValue = ChooseEq.create()
                .when(carInfo, "1", "2")
                .when(carInfo, "2", "1")
                .when(carInfo, "3", "1")
                .when(carInfo, "4", "1")
                .end("1");
        apiPlatDataExchange.setCarInfo(carInfoValue);

        // hasCompany 职业  1(上班族) 2（自由职业）3（私营企业主）4（公务员/国企）
        // career
        //   1	上班族
        //   2	自由职业
        //   3	企业主（有营业执照）
        //   4	公务员或事业单位
        //   5	个体户
        String career = apiDataChangeMessage.getCareer();
        String careerValue = ChooseEq.create()
                .when(career, "1", "1")
                .when(career, "2", "2")
                .when(career, "3", "3")
                .when(career, "4", "4")
                .when(career, "5", "2")
                .end("2");
        apiPlatDataExchange.setCareer(careerValue);

        // commericalInsurance 保单0（6个月以下）1（6-12个月）2（12个月以上）3（无）
        // insurancePolicy 保险保单
        // 1 无保险保单
        // 2 缴纳未满1年
        // 3 缴纳1年以上
        // 4 有保险保单
        String insurancePolicy = apiDataChangeMessage.getInsurancePolicy();
        String insurancePolicyValue = ChooseEq.create()
                .when(insurancePolicy, "1", "3")
                .when(insurancePolicy, "2", "1")
                .when(insurancePolicy, "3", "2")
                .when(insurancePolicy, "4", "1")
                .end("0");
        apiPlatDataExchange.setInsurancePolicy(insurancePolicyValue);

        // 社保1（6个月以下）2（6-12个月）3（12个月以上）4（无）
        // socialSecurity 社保缴纳
        // 1 无社保
        // 2 缴纳6个月以下
        // 3 缴纳6个月以上
        // 4 有社保
        String socialSecurity = apiDataChangeMessage.getSocialSecurity();
        String socialSecurityValue = ChooseEq.create()
                .when(socialSecurity, "1", "4")
                .when(socialSecurity, "2", "1")
                .when(socialSecurity, "3", "2")
                .when(socialSecurity, "4", "1")
                .end("0");
        apiPlatDataExchange.setSocialSecurity(socialSecurityValue);

        // hasFund 是否有公积金，1-有、0-无
        // providentFund 公积金
        // 1 无公积金
        // 2 缴纳6个月以下
        // 3 缴纳6个月以上
        // 4 有公积金
        String providentFund = apiDataChangeMessage.getProvidentFund();
        String providentFundValue = ChooseEq.create()
                .when(providentFund, "1", "4")
                .when(providentFund, "2", "1")
                .when(providentFund, "3", "2")
                .when(providentFund, "4", "1")
                .end("4");
        apiPlatDataExchange.setProvidentFund(providentFundValue);

        // zhima 芝麻分 1（600-650）2（650-700）3（700以上）4（无）5（600以下）
        // sesameCredit 芝麻分
        // 1 600分以下
        // 2 600~649分
        // 3 650~699分
        // 4 700分以上
        String sesameCredit = apiDataChangeMessage.getSesameCredit();
        String sesameCreditValue = ChooseEq.create()
                .when(sesameCredit, "1", "5")
                .when(sesameCredit, "2", "1")
                .when(sesameCredit, "3", "2")
                .when(sesameCredit, "4", "3")
                .end("4");
        apiPlatDataExchange.setSesameCredit(sesameCreditValue);

        // 贷款时间2（6个月）3（12个月）4（24个月）5（36个月）
        // 贷款期限
        // 1.3个月
        // 2.6个月
        // 3.12个月
        // 4.24个月
        // 5.36个月
        // 6.60个月
        String loanTime = apiDataChangeMessage.getLoanTerm();
        String loanTimeValue = ChooseEq.create()
                .when(loanTime, "2", "2")
                .when(loanTime, "3", "3")
                .when(loanTime, "4", "4")
                .when(loanTime, "5", "5")
                .end("1");
        apiPlatDataExchange.setLoanTerm(loanTimeValue);

        // overdue 逾期记录1（信用良好）2（当前逾期中）
        // overdue 信用情况（逾期）
        // 1.无逾期
        // 2.当前有逾期
        // 3.一年以内无逾期
        String overdue = apiDataChangeMessage.getOverdue();
        String overdueValue = ChooseEq.create()
                .when(overdue, "1", "1")
                .when(overdue, "2", "2")
                .when(overdue, "3", "3")
                .when(overdue, "4", "4")
                .end("1");
        apiPlatDataExchange.setOverdue(overdueValue);
        apiPlatDataExchange.setIp("127.0.0.1");

        apiPlatDataExchange.setAppKey(APP_KEY);
        Map<String, Object> ObjectMap = MapUtils.newHashMap(newMap -> {
            newMap.put("orgId", CHANNEL_CODE);
            newMap.put("data", encrypt(KEY,JsonUtils.toJson(apiPlatDataExchange)));
        });
        return JsonUtils.toJson(ObjectMap);
    }


    @Override
    public Object apply(ApiApplyParameter apiApplyMessage) throws Exception {

        ApiPlatApplyJiYongHua apiPlatApply = new ApiPlatApplyJiYongHua();

        apiPlatApply.setUserName(apiApplyMessage.getUserName());

        apiPlatApply.setPhone(apiApplyMessage.getPhone());
        // 城市代码
        apiPlatApply.setAreaCode(apiApplyMessage.getAreaCode());
        // 城市
        apiPlatApply.setCity(apiApplyMessage.getCity());

        //  年龄(21岁-55岁)
        String age = ApiDictUtils.convertAge(apiApplyMessage.getAge());
        apiPlatApply.setAge(age);

        //sex 性别(1:为男,2:为女)
        // sex 性别
        // 0 男
        // 1 女
        // 2 未知
        String sex = apiApplyMessage.getSex();
        String sexChoose = ChooseEq.create()
                .when(sex, "0", "1")
                .when(sex, "1", "2")
                .end("1");
        apiPlatApply.setSex(sexChoose);

        // loanAmount 贷款额度1（30000）2（50000）3（100000）4（200000）
        // loanAmount 贷款金额
        // 1 3万以下
        // 2 5万-10万
        // 3 10万-20万
        // 4 20万以上
        String loanAmount = apiApplyMessage.getLoanAmount();
        String loanAmountValue = ChooseEq.create()
                .when(loanAmount, "1", "1")
                .when(loanAmount, "2", "2")
                .when(loanAmount, "3", "3")
                .when(loanAmount, "4", "4")
                .end("1");
        apiPlatApply.setLoanAmount(loanAmountValue);

        // hasHouse 是否有房，1-有、0-无
        // realEstateInfo 房产情况
        // 1 无房产
        // 2 有房不抵押
        // 3 有房可抵押
        // 4 有房产
        // 5 有按揭房产
        // 6 有全款房产
        String realEstateInfo = apiApplyMessage.getRealEstateInfo();
        String realEstateInfoValue = ChooseEq.create()
                .when(realEstateInfo, "1", "0")
                .when(realEstateInfo, "2", "1")
                .when(realEstateInfo, "3", "1")
                .when(realEstateInfo, "4", "1")
                .when(realEstateInfo, "5", "1")
                .when(realEstateInfo, "6", "1")
                .end("0");
        apiPlatApply.setRealEstateInfo(realEstateInfoValue);

        // vehicle 名下车产1（有车产）2（无车产）
        // carInfo 车辆情况
        // 1 无车产
        // 2 有车不抵押
        // 3 有车可抵押
        // 4 有车产
        String carInfo = apiApplyMessage.getCarInfo();
        String carInfoValue = ChooseEq.create()
                .when(carInfo, "1", "2")
                .when(carInfo, "2", "1")
                .when(carInfo, "3", "1")
                .when(carInfo, "4", "1")
                .end("1");
        apiPlatApply.setCarInfo(carInfoValue);

        // hasCompany 职业  1(上班族) 2（自由职业）3（私营企业主）4（公务员/国企）
        // career
        //   1	上班族
        //   2	自由职业
        //   3	企业主（有营业执照）
        //   4	公务员或事业单位
        //   5	个体户
        String career = apiApplyMessage.getCareer();
        String careerValue = ChooseEq.create()
                .when(career, "1", "1")
                .when(career, "2", "2")
                .when(career, "3", "3")
                .when(career, "4", "4")
                .when(career, "5", "2")
                .end("2");
        apiPlatApply.setCareer(careerValue);

        // commericalInsurance 保单0（6个月以下）1（6-12个月）2（12个月以上）3（无）
        // insurancePolicy 保险保单
        // 1 无保险保单
        // 2 缴纳未满1年
        // 3 缴纳1年以上
        // 4 有保险保单
        String insurancePolicy = apiApplyMessage.getInsurancePolicy();
        String insurancePolicyValue = ChooseEq.create()
                .when(insurancePolicy, "1", "3")
                .when(insurancePolicy, "2", "1")
                .when(insurancePolicy, "3", "2")
                .when(insurancePolicy, "4", "1")
                .end("0");
        apiPlatApply.setInsurancePolicy(insurancePolicyValue);

        // 社保1（6个月以下）2（6-12个月）3（12个月以上）4（无）
        // socialSecurity 社保缴纳
        // 1 无社保
        // 2 缴纳6个月以下
        // 3 缴纳6个月以上
        // 4 有社保
        String socialSecurity = apiApplyMessage.getSocialSecurity();
        String socialSecurityValue = ChooseEq.create()
                .when(socialSecurity, "1", "4")
                .when(socialSecurity, "2", "1")
                .when(socialSecurity, "3", "2")
                .when(socialSecurity, "4", "1")
                .end("0");
        apiPlatApply.setSocialSecurity(socialSecurityValue);

        // hasFund 是否有公积金，1-有、0-无
        // providentFund 公积金
        // 1 无公积金
        // 2 缴纳6个月以下
        // 3 缴纳6个月以上
        // 4 有公积金
        String providentFund = apiApplyMessage.getProvidentFund();
        String providentFundValue = ChooseEq.create()
                .when(providentFund, "1", "4")
                .when(providentFund, "2", "1")
                .when(providentFund, "3", "2")
                .when(providentFund, "4", "1")
                .end("4");
        apiPlatApply.setProvidentFund(providentFundValue);

        // zhima 芝麻分 1（600-650）2（650-700）3（700以上）4（无）5（600以下）
        // sesameCredit 芝麻分
        // 1 600分以下
        // 2 600~649分
        // 3 650~699分
        // 4 700分以上
        String sesameCredit = apiApplyMessage.getSesameCredit();
        String sesameCreditValue = ChooseEq.create()
                .when(sesameCredit, "1", "5")
                .when(sesameCredit, "2", "1")
                .when(sesameCredit, "3", "2")
                .when(sesameCredit, "4", "3")
                .end("4");
        apiPlatApply.setSesameCredit(sesameCreditValue);

        // overdue 逾期记录1（信用良好）2（当前逾期中）
        // overdue 信用情况（逾期）
        // 1.无逾期
        // 2.当前有逾期
        // 3.一年以内无逾期
        String overdue = apiApplyMessage.getOverdue();
        String overdueValue = ChooseEq.create()
                .when(overdue, "1", "1")
                .when(overdue, "2", "2")
                .when(overdue, "3", "3")
                .when(overdue, "4", "4")
                .end("1");
        apiPlatApply.setOverdue(overdueValue);
        apiPlatApply.setIp("127.0.0.1");

        apiPlatApply.setAppKey(APP_KEY);

        Map<String, Object> ObjectMap = MapUtils.newHashMap(newMap -> {
            newMap.put("orgId", CHANNEL_CODE);
            newMap.put("data", encrypt(KEY,JsonUtils.toJson(apiPlatApply)));
        });
        return JsonUtils.toJson(ObjectMap);
    }

    @Override
    public RespPlatformPhoneMd5Apply respApply(String respJson) throws Exception {
        JSONObject jsonObject = JsonUtils.get(respJson);
        if (jsonObject == null) {
            return RespPlatformPhoneMd5Apply.ofFail();
        }
        String code = jsonObject.getString("code");
        if (!Eq.str(code, "0")) {
            return RespPlatformPhoneMd5Apply.ofFail();
        }
        return RespPlatformPhoneMd5Apply.ofSuc();
    }

    @Override
    public RespPlatformNoticeApply parseApplyNotice(RequestVO requestVO) {
        return null;
    }

    @Override
    public Map<String, Object> respApplyNotice(ApiBizStatus apiBizStatus) {
        return Map.of();
    }

    public String encrypt(String key,String str){
        try {
            if(Objects.isNull(str)){
                return "";
            }
            byte[] bytes = key.getBytes(StandardCharsets.UTF_8);
            SecretKeySpec keySpec = new SecretKeySpec(bytes, "AES");
            Cipher instance = Cipher.getInstance("AES/ECB/PKCS5Padding");
            instance.init(Cipher.ENCRYPT_MODE, keySpec);
            byte[] doFinal = instance.doFinal(str.getBytes(StandardCharsets.UTF_8));
            return Base64.getEncoder().encodeToString(doFinal);
        } catch (Exception e) {
            log.error("加密失败", e);
            throw new RuntimeException(e);
        }
    }
}
